package com.mingtu.guards.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.CustomDecoration;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.TaskCarryOut1Adapter;
import com.mingtu.guards.adapter.TaskCarryOut2Adapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.TemporaryTaskBean;
import com.mingtu.guards.share.BottomPopupShare;
import com.mingtu.guards.utils.MyConstant;
import com.mob.MobSDK;
import com.mob.moblink.ActionListener;
import com.mob.moblink.MobLink;
import com.mob.moblink.Scene;
import com.mob.moblink.SceneRestorable;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.favorite.WechatFavorite;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

public class TaskDetails1Activity extends MyBaseActivity implements SceneRestorable {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_time_start)
    TextView tvTimeStart;
    @BindView(R.id.tv_time_end)
    TextView tvTimeEnd;
    @BindView(R.id.recycler1)
    RecyclerView recycler1;
    @BindView(R.id.recycler2)
    RecyclerView recycler2;
    @BindView(R.id.empty_layout1)
    EmptyDataLayout emptyLayout1;
    @BindView(R.id.empty_layout2)
    EmptyDataLayout emptyLayout2;
    @BindView(R.id.layout_finish)
    FrameLayout layoutFinish;
    @BindView(R.id.layout_unfinish)
    FrameLayout layoutUnfinish;
    @BindView(R.id.iv_eyes)
    ImageView ivEyes;
    @BindView(R.id.tv_people)
    TextView tvPeople;
    @BindView(R.id.tv_task_content)
    TextView tvTaskContent;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private String taskId;
    private TaskCarryOut1Adapter taskCarryOut1Adapter;
    private TaskCarryOut2Adapter taskCarryOut2Adapter;
    private List<TemporaryTaskBean.DataBean.AssignmentUserEntityListBean> DataBean1 = new ArrayList<>();
    private List<TemporaryTaskBean.DataBean.AssignmentUserEntityListBean> DataBean2 = new ArrayList<>();
    private String[] peopleArray = null;
    private BasePopupView popupView;
    private String taskMemo = "";
    private String myPath = "";
    private String taskType;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_task_details1;
    }

    @Override
    protected void initView() {
        //此页面已经改为临时任务的详情
        setModuleTitle("任务详情");
        setTitleBarBackground(getResources().getDrawable(R.drawable.titlebar_line_bottom));
        showTopRightImg(R.mipmap.icon_share_black);
    }

    @Override
    protected void initData() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler1.setLayoutManager(manager1);
//        recycler1.addItemDecoration(new SpacesItemDecoration(0, 0, 15, 15, 15));
        //添加自定义分割线
        recycler1.addItemDecoration(new CustomDecoration(context, CustomDecoration.VERTICAL_LIST, R.drawable.shape_dive_line, 0));
        LinearLayoutManager manager2 = new LinearLayoutManager(context);
        recycler2.setLayoutManager(manager2);
//        recycler2.addItemDecoration(new SpacesItemDecoration(0, 0, 15, 15, 15));
        recycler2.addItemDecoration(new CustomDecoration(context, CustomDecoration.VERTICAL_LIST, R.drawable.shape_dive_line, 0));


        taskCarryOut1Adapter = new TaskCarryOut1Adapter(context, DataBean1);
        recycler1.setAdapter(taskCarryOut1Adapter);

        taskCarryOut2Adapter = new TaskCarryOut2Adapter(context, DataBean2);
        recycler2.setAdapter(taskCarryOut2Adapter);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_finish:
                        setTabSelect(0);
                        break;
                    case R.id.rb_unfinish:
                        setTabSelect(1);
                        break;
                }
            }
        });


//        MobclickLink.handleUMLinkURI(this, getIntent().getData(), umlinkAdapter);
//        boolean hasGetInstallParams = SPStaticUtils.getBoolean(MySPTools.Has_Get_Install_Params, false);
//        if (hasGetInstallParams == false) {
//            //从来没调用过getInstallParam方法，适当延时调用getInstallParam方法
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    MobclickLink.getInstallParams(context, umlinkAdapter);
//                }
//            }, 2000);//2秒后执行
//            //MobclickLink.getInstallParams(mContext, umlinkAdapter);
//
//            //在9.3.3版本中，由于要检查SDK是否初始化成功，所以可能需要3秒乃至更长的延迟才能调用getInstallParams
//            //在9.3.6以后版本中，不再检查SDK是否初始化成功，可以不用延迟
//
//        } else {
//            //已经调用过getInstallParam方法，没必要在下次启动时再调用
//            //但后续仍可在需要时调用，比如demo中的按钮点击
//        }

    }

    @Override
    protected void getData() {
        if (StringUtils.isEmpty(myPath)) { //myPath不为空的时候是通过分享页面进入此页面的
            taskId = getIntent().getStringExtra("taskId");
            taskType = getIntent().getStringExtra("taskType");
            if (!StringUtils.isEmpty(taskId)) {
                getTaskDetails();
            } else {
                ToastUtils.showLong(getResources().getString(R.string.data_error));
            }
        }
    }

    @OnClick({R.id.iv_eyes})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_eyes:
                if (peopleArray != null) {
                    if (peopleArray.length > 0) {
                        new XPopup.Builder(this)
                                //                        .maxWidth(600)
                                .maxHeight(1000)
                                .isDarkTheme(false)
                                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                                .asCenterList("接收人员", peopleArray,
                                        new OnSelectListener() {
                                            @Override
                                            public void onSelect(int position, String text) {

                                            }
                                        })
                                .show();
                    }
                }
                break;
        }
    }

    @Override
    protected void onClickedTopLeftButtton(View view) {
        if (!StringUtils.isEmpty(myPath)) {
            //从分享页面跳转过来
            IntentUtils.getInstance().readyGo(TaskDetails1Activity.this, MainActivity.class);
        }
        super.onClickedTopLeftButtton(view);
    }

    @Override
    protected void onClickTitlebarRight(View view) {
        super.onClickTitlebarRight(view);
        //分享
        BottomPopupShare bottomPopup = new BottomPopupShare(this);
        bottomPopup.setOnItemClickListener(new BottomPopupShare.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                popupView.dismiss();
//                UMImage image = new UMImage(TaskDetails1Activity.this, R.mipmap.ic_launcher);//资源文件
//                image.compressFormat = Bitmap.CompressFormat.PNG;
//                UMWeb web = new UMWeb(MyConstant.SHARE_URL + "id=" + taskId);
//                web.setTitle("下发任务");//标题
//                web.setThumb(image);//缩略图
//                web.setDescription(taskMemo);//描述
//                ShareAction shareAction = new ShareAction(TaskDetails1Activity.this);
//                if (position == 0) {
//                    //好友
//                    //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
//                    shareAction.setPlatform(SHARE_MEDIA.WEIXIN);
//
//                } else if (position == 1) {
//                    //朋友圈
//                    shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE);
//                } else if (position == 2) {
//                    //收藏
//                    shareAction.setPlatform(SHARE_MEDIA.WEIXIN_FAVORITE);
//                }
//                shareAction.withMedia(web);
//                shareAction.share();

                // 设置场景参数
                HashMap<String, Object> senceParams = new HashMap();
                senceParams.put("id", taskId);// 新建场景
                Scene s = new Scene();
                s.path = MyConstant.getInstance().TASK_DETAILS_PATH;
                s.params = senceParams;
                // 请求场景ID
                MobLink.getMobID(s, new ActionListener<String>() {
                    @Override
                    public void onResult(String s) {
                        String mobID = s;
                        if (StringUtils.isEmpty(taskMemo)) {
                            taskMemo = "绿水青山就是金山银山";
                        }
                        Bitmap imageData = MyUtills.drawable2Bitmap(context.getResources().getDrawable(R.drawable.bg_shared_img));
                        final OnekeyShare oks = new OnekeyShare();
                        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
                        // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
                        oks.setTitleUrl("https://www.mingtukeji.com");
                        // text是分享文本，所有平台都需要这个字段
                        oks.setText(taskMemo);
                        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//                        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
                        // url仅在微信（包括好友和朋友圈）中使用
                        oks.setImageData(imageData);
                        oks.setUrl("https://www.mingtukeji.com/jzApp/task_share.html?mobid=" + mobID);
                        if (position == 0) {
                            //好友
                            //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
                            oks.setTitle("下发任务");
                            oks.setPlatform(Wechat.NAME);
                            oks.show(MobSDK.getContext());
                        } else if (position == 1) {
                            //朋友圈
                            oks.setTitle(taskMemo);
                            oks.setPlatform(WechatMoments.NAME);
                            oks.show(MobSDK.getContext());
                        } else if (position == 2) {
                            //收藏
                            oks.setTitle(taskMemo);
                            oks.setPlatform(WechatFavorite.NAME);
                            oks.show(MobSDK.getContext());
                        }

                    }

                    @Override
                    public void onError(Throwable throwable) {

                    }
                });


            }
        });
        popupView = new XPopup.Builder(this)
                .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                .enableDrag(true)
                .isDarkTheme(true)
                .navigationBarColor(getResources().getColor(R.color.black))
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isThreeDrag(true) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                .asCustom(bottomPopup)
                .show();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        MobLink.updateNewIntent(getIntent(), this);
        //友盟
        //Uri uri = intent.getData();
        // 此处要调用，否则App在后台运行时，会无法截获
        //MobclickLink.handleUMLinkURI(this, intent.getData(), umlinkAdapter);
    }

    @Override
    public void onReturnSceneData(Scene scene) {
        if (scene != null) {
            myPath = scene.getPath();
            HashMap<String, Object> hashMap = scene.getParams();
            if (hashMap != null) {
                if (hashMap.containsKey("id")) {
                    taskId = String.valueOf(hashMap.get("id"));
                    getTaskDetails();
                }
            }
        }
    }


    /**
     * 点击完成、未完成
     *
     * @param type
     */
    public void setTabSelect(int type) {
        if (type == 0) {
            layoutFinish.setVisibility(View.VISIBLE);
            layoutUnfinish.setVisibility(View.GONE);
        } else if (type == 1) {
            layoutFinish.setVisibility(View.GONE);
            layoutUnfinish.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 任务详情
     */
    private void getTaskDetails() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", taskId);
        hashMap.put("type", taskType);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_SUPER_DETAILS)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                TemporaryTaskBean temporaryTaskBean = new TemporaryTaskBean();
                                temporaryTaskBean = gson.fromJson(result, TemporaryTaskBean.class);
                                TemporaryTaskBean.DataBean dataBean = temporaryTaskBean.getData();
                                List<TemporaryTaskBean.DataBean.AssignmentUserEntityListBean> entityListBeans = dataBean.getAssignmentUserEntityList();

                                List<TemporaryTaskBean.DataBean.AssignmentUserEntityListBean> unFinishBeans = new ArrayList<>();
                                List<TemporaryTaskBean.DataBean.AssignmentUserEntityListBean> finishBeans = new ArrayList<>();

                                String taskName = dataBean.getName(); // 任务名字
                                // 任务内容
                                taskMemo = dataBean.getMemo();
                                String createTime = dataBean.getCreateTime(); // 任务创建时间
                                String finishTime = dataBean.getFinishTime(); // 任务截止时间

                                if (!StringUtils.isEmpty(taskName)) {
                                    tvTitle.setText(taskName);
                                }
                                if (!StringUtils.isEmpty(createTime)) {
                                    tvTimeStart.setText(createTime);
                                }
                                if (!StringUtils.isEmpty(finishTime)) {
                                    tvTimeEnd.setText(finishTime);
                                }
                                if (!StringUtils.isEmpty(taskMemo)) {
                                    tvTaskContent.setText(taskMemo);
                                }

                                if (entityListBeans != null) {
                                    int size = entityListBeans.size();
                                    if (size > 0) {
                                        String str = "";
                                        peopleArray = new String[size];
                                        for (int i = 0; i < size; i++) {
                                            TemporaryTaskBean.DataBean.AssignmentUserEntityListBean bean = entityListBeans.get(i);
                                            int status = bean.getStatus();
                                            String name = bean.getName();
                                            peopleArray[i] = name; //接收人员 数组
                                            if (status == 0) {
                                                unFinishBeans.add(bean);
                                            } else if (status == 1) {
                                                finishBeans.add(bean);
                                            }
                                        }


                                        if (size == 1) {
                                            str = peopleArray[0];
                                        }
                                        if (size > 1 && size <= 3) {
                                            for (int i = 0; i < size; i++) {
                                                String name = peopleArray[i];
                                                if (i < peopleArray.length - 1) {
                                                    name = name + "，";
                                                }
                                                str += name;
                                            }
                                        }

                                        if (size > 3) {
                                            String myArray[] = Arrays.copyOfRange(peopleArray, 0, 3);
                                            for (int i = 0; i < myArray.length; i++) {
                                                String name = myArray[i];
                                                if (i < myArray.length - 1) {
                                                    name = name + "，";
                                                }
                                                str += name;
                                            }
                                        }

                                        if (size > 3) {
                                            ivEyes.setVisibility(View.VISIBLE);
                                            tvPeople.setText(str + "等" + size + "人");
                                        } else {
                                            tvPeople.setText(str);
                                        }

                                    }
                                }

                                if (finishBeans.size() > 0) {
                                    taskCarryOut1Adapter.upData(finishBeans);
                                } else {
                                    emptyLayout1.setIsShowView(true);
                                }


                                if (unFinishBeans.size() > 0) {
                                    taskCarryOut2Adapter.upData(unFinishBeans);
                                } else {
                                    emptyLayout2.setIsShowView(true);
                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });
    }


//    private UMLinkListener umlinkAdapter = new UMLinkListener() {
//        @Override
//        public void onLink(String path, HashMap<String, String> queryParams) {
//            if (!path.isEmpty()) {
//                //此处获得path即为后台配置的页面path
//                myPath = path;
//            }
//            if (!queryParams.isEmpty()) {
//                //此处获得query_params即为后台配置的页面启动唤起的参数kv键值对
//                taskId = queryParams.get("id");
//                if (!StringUtils.isEmpty(taskId)) {
//                    getTaskDetails();
//                }
//            }
//            //针对path和query_params做页面跳转等处理
//        }
//
//        @Override
//        public void onInstall(HashMap<String, String> installParams, Uri uri) {
//            if (installParams.isEmpty() && uri.toString().isEmpty()) {
//                //没有匹配到新装参数，示例弹框
//                AlertDialog.Builder builder = new AlertDialog.Builder(context);
//                builder.setMessage("没有匹配到新装参数");
//                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int whichButton) {
//                    }
//                });
//                builder.show();
//            } else {
//                if (!installParams.isEmpty()) {
//                    //此处获得install_params即为配置的新装参数kv键值对
//                }
//                if (!uri.toString().isEmpty()) {
//                    //可将uri交给handleUMLinkURI处理，回调至onLink
//                    MobclickLink.handleUMLinkURI(context, uri, umlinkAdapter);
//                }
//            }
//
//            SPStaticUtils.put(MySPTools.Has_Get_Install_Params, true);
//        }
//
//        @Override
//        public void onError(String error) {
//            //发生网络错误或超时等异常，示例弹框
//            AlertDialog.Builder builder = new AlertDialog.Builder(context);
//            builder.setMessage(error);
//            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int whichButton) {
//                }
//            });
//            builder.show();
//        }
//    };


}